﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using T.ServiceComponent.I18N.Service;

namespace T.FAS.Runtime.Base.Entity
{
    /// <summary>
    /// 基础类型数据
    /// </summary>
    public static class BasicTypeData
    {
        public static readonly string DefaultPropertyName = "Data";
        public static TSchema BuildSchema(string dataType)
        {
            try
            {
                TSchema schema = new TSchema
                {
                    MetadataType = TEntityType.BasicType,
                };
                schema.Entity = new TEntity()
                {
                    MetadataID = DefaultPropertyName,
                    MetadataCode = DefaultPropertyName,
                    MetadataName = DefaultPropertyName,
                    MetadataType = TEntityType.BasicType,
                    Description = DefaultPropertyName,
                    Attributes = new List<TAttribute>()
                    {
                        new TAttribute()
                        {
                            ID = Guid.NewGuid().ToString(),
                            Code = DefaultPropertyName,
                            Name = DefaultPropertyName,
                            Description = DefaultPropertyName,
                            DataType = ToEnum<DataType>(dataType),
                        }
                    }
                };
                return schema;
            }
            catch (Exception e)
            {
                throw new FasException(BaseExceptionCode.TSchemaBuildError, $"{TermService.Current.GetTextFormatted("T_FAS_fasr_Base_559322950", "构造数据类型{0}的Schema异常，{1}", dataType, e.ToString())}");
            }
        }

        public static T ToEnum<T>(this string name) where T : struct
        {
            if (Enum.TryParse(name, out T result))
            {
                return result;
            }
            throw new Exception($"转化枚举值失败,类型:{typeof(T).Name},输入值:{name}");
        }
    }
}
